package cav;

public class GenerateurCaverne
{
	public static int TAILLE = 128;
	public static int SEUIL = 45;

	public static boolean[][] getCavern() {
		boolean[][] result = new boolean[TAILLE][TAILLE];
		// boucle init
		for (int i = 0; i < result[0].length; i++)
		{
			for (int j = 0; j < result.length; j++)
			{
				result[i][j] = (((int) (Math.random() * 100)) > SEUIL ? false
						: true);
			}
		}// TEST
		for (int i = 0; i < 5; i++)
		{
			result = generation(result, 5, -1);
		}
//		for (int i = 0; i < 10; i++)
//		{
//			result = generation(result, 5, -1);
//		}
		for (int i = 0; i < 1; i++)
		{
			result = generation(result, 5, 0);
		}
		return result;
	}

	public static boolean[][] generation(boolean[][] pTabResult, int r1, int r2) {
		boolean[][] result = new boolean[pTabResult.length][pTabResult.length];
		// boucle
		for (int i = 0; i < pTabResult[0].length; i++)
		{
			for (int j = 0; j < pTabResult.length ; j++)
			{
				int v1 = calculV1(pTabResult, i, j);
				int v2 = calculV2(pTabResult, i, j);
				if (v1 >= r1)
				{
					result[i][j] = true;
				}
				else if (v2 <= r2)
				{
					result[i][j] = true;
				}
				else
				{
					result[i][j] = false;
				}
			}
		}
		return result;
	}

	public static int calculV1(boolean[][] map, int i, int j) {
		int nb = 0;
		if (i + 1 < map.length)
		{
			nb = nb + (map[i + 1][j] ? 1 : 0);
			nb = nb + (j + 1 < map.length && map[i + 1][j + 1] ? 1 : 0);
			nb = nb + (j - 1 >= 0 && map[i + 1][j - 1] ? 1 : 0);
		}
		nb = nb + (j - 1 >= 0 && map[i][j - 1] ? 1 : 0);
		nb = nb + (j + 1 < map.length &&map[i][j + 1] ? 1 : 0);
		if (i - 1 >= 0)
		{
			nb = nb + (map[i - 1][j] ? 1 : 0);
			nb = nb + (j - 1 >= 0 && map[i - 1][j - 1] ? 1 : 0);
			nb = nb + (j + 1 < map.length && map[i - 1][j + 1] ? 1 : 0);
		}
		return nb;
	}

	public static int calculV2(boolean[][] map, int i, int j) {
		int nb = calculV1(map, i, j);
		if (i + 2 < map.length)
		{
			nb = nb + (map[i + 2][j] ? 1 : 0);
			nb = nb + (j + 1 < map.length && map[i + 2][j + 1] ? 1 : 0);
			nb = nb + (j - 1 >= 0 && map[i + 2][j - 1] ? 1 : 0);
		}
		if (i - 2 >= 0)
		{
			nb = nb + (map[i - 2][j] ? 1 : 0);
			nb = nb + (j + 1 < map.length && map[i - 2][j + 1] ? 1 : 0);
			nb = nb + (j - 1 >= 0 && map[i - 2][j - 1] ? 1 : 0);
		}
		if (j + 2 < map.length)
		{
			nb = nb + (i - 1 >= 0 && map[i - 1][j + 2] ? 1 : 0);
			nb = nb + (map[i][j + 2] ? 1 : 0);
			nb = nb + (i + 1 < map.length && map[i + 1][j + 2] ? 1 : 0);
		}
		if (j - 2 >= 0)
		{
			nb = nb + (i - 1 >= 0 && map[i - 1][j - 2] ? 1 : 0);
			nb = nb + (map[i][j - 2] ? 1 : 0);
			nb = nb + (i + 1 < map.length && map[i + 1][j - 2] ? 1 : 0);
		}
		return nb;
	}
}
